/*
 * @Description: 项目管理
 * @Author: DSY
 * @Date: 2022-03-14 21:48:53
 * @LastEditors: DHL
 * @LastEditTime: 2023-01-31 11:31:38
 */

import { defineComponent, computed, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { cloneDeep, assign } from 'lodash-es'
import { ProjectModel } from '@/api/system/model/projectModel'
import { apiProjectSave, apiProjectUpdateById } from '@/api/system/project'
import { log } from '../../../utils/logUtils'

export default defineComponent({
  name: 'ProjectForm',
  emits: ['refreshTableData'],
  setup(props, { emit, expose }) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////
    const dbFormRef = ref()
    const loading = ref(true)

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 显示弹框
     */
    const visible = ref(false)

    /**
     * 标题
     */
    const title = computed(() => {
      let rtn = ''
      switch (action.value) {
        case 'add':
          rtn = '新增'
          break
        case 'edit':
          rtn = '编辑'
          break
        default:
          rtn = '查看'
          break
      }
      return rtn
    })

    //////////////////////////////////////////////////
    // 表单
    //////////////////////////////////////////////////

    const defaultForm = {
      name: '', // 项目名称
      code: '', // 项目编码
      appId: '', // 接入ID
      appToken: '', // 接入Token
      appSecret: '', // 接入密钥
      appType: '', // 项目类型（1，服务端；2，微信小程序；3，手机app；4，网页）
      ipAddr: '', // IP地址
      portCode: '', // 端口号
      webAddr: '', // 域名
      status: '1', // 接入状态(0,不允许接入;1,允许接入)
      remark: '' // 备注
    }

    let dbForm = reactive<ProjectModel>(cloneDeep(defaultForm))

    //////////////////////////////////////////////////
    // 表单验证规则
    //////////////////////////////////////////////////

    /**
     * 表单验证规则
     */
    const rules = reactive({
      name: [
        {
          required: true,
          message: '请输入项目名称',
          trigger: 'blur'
        }
      ],
      appId: [
        {
          required: true,
          message: '请输入接入ID',
          trigger: 'blur'
        }
      ],
      appToken: [
        {
          required: true,
          message: '请输入接入Token',
          trigger: 'blur'
        }
      ],
      appType: [
        {
          required: true,
          message: '请选择项目类型',
          trigger: 'blur'
        }
      ],
      ipAddr: [
        {
          required: false,
          message: '请输入IP地址',
          trigger: 'blur'
        }
      ],
      portCode: [
        {
          required: false,
          message: '请输入端口号',
          trigger: 'blur'
        }
      ],
      webAddr: [
        {
          required: false,
          message: '请输入域名',
          trigger: 'blur'
        }
      ],
      proSeq: [
        {
          required: false,
          message: '请输入顺序号',
          trigger: 'blur'
        }
      ],
      status: [
        {
          required: false,
          message: '请选择接入状态',
          trigger: 'blur'
        }
      ],
      remark: [
        {
          required: false,
          message: '请输入备注',
          trigger: 'blur'
        }
      ]
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 打开弹框
     */
    function handleOpen(actionParam: string, rowParam?: ProjectModel) {
      visible.value = true
      loading.value = false
      action.value = actionParam
      if (['edit', 'view'].indexOf(actionParam) > -1 && rowParam) {
        assign(dbForm, cloneDeep(rowParam))
      }
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      assign(dbForm, cloneDeep(defaultForm))
      visible.value = false
    }

    /**
     * 提交表单
     */
    function handleSubmit(isContinue: boolean) {
      assign(dbForm, {
        code: dbForm.appId
      })
      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          if (action.value === 'add') {
            addFun(isContinue)
          } else {
            editFun()
          }
        } else {
          log.warn('项目管理', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun(isContinue: boolean) {
      loading.value = true
      apiProjectSave(dbForm)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)

            handleReset(!isContinue)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun() {
      loading.value = true
      apiProjectUpdateById(dbForm)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)

            handleReset(true)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 重置表单
     * @param isClosed 是否关闭弹框
     */
    function handleReset(isClosed: boolean) {
      assign(dbForm, cloneDeep(defaultForm))
      if (isClosed) {
        emit('refreshTableData')
        visible.value = false
      }
    }

    /**
     * 暴露函数
     */
    expose({ handleOpen })

    return {
      loading,
      visible,
      action,
      title,
      dbFormRef,
      dbForm,
      rules,
      handleOpen,
      handleClose,
      handleSubmit,
      handleReset
    }
  }
})
